package td3.view;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JTextPane;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;

import td3.model.AppModel;
import td3.model.ContactFileTransferHandler;
import td3.model.ContactTreeModel;

public class ContactTextPane extends JTextPane {

	private static final long serialVersionUID = -3250384857557985116L;

	private final AppModel appModel;

	public ContactTextPane(AppModel appModel) {
		this.appModel = appModel;
		this.setTransferHandler(new ContactFileTransferHandler(appModel));
		appModel.addPropertyChangeListener(new PropertyChangeListener() {

			@Override
			public void propertyChange(PropertyChangeEvent event) {
				if (event.getPropertyName().equals(
						AppModel.Property.CONTACT_TREE_MODEL.name())) {
					ContactTreeModel contactTreeModel = (ContactTreeModel) event
							.getNewValue();
					try {
						String xml = contactTreeModel.toXml();
						setText(xml);
					} catch (Exception e) {
						System.out.println("XML PARSING FAILED");
					}
				}
			}
		});

		this.appModel.getContactTreeModel().addTreeModelListener(
				new TreeModelListener() {
					private void rebuildXML() {
						try {
							String xml = ContactTextPane.this.appModel
									.getContactTreeModel().toXml();
							setText(xml);
						} catch (Exception e) {
							System.out.println("XML PARSING FAILED");
						}
					}
					
					@Override
					public void treeStructureChanged(TreeModelEvent arg0) {
						rebuildXML();
					}

					@Override
					public void treeNodesRemoved(TreeModelEvent arg0) {
						rebuildXML();
					}

					@Override
					public void treeNodesInserted(TreeModelEvent arg0) {
						rebuildXML();
					}

					@Override
					public void treeNodesChanged(TreeModelEvent arg0) {
						rebuildXML();
					}
				});
	}

}
